package my.location;

import java.util.Iterator;
import java.util.List;

import my.location.locationPolicy.DefinedAction;
import my.location.locationPolicy.DefinedLocation;
import my.location.locationPolicy.LocationPolicy;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class LocationService extends Service{
	 private static final String TAG = "MyService";  
	 private LocationManager locationManager;
	 private Location baseLocation;
	 private List<LocationPolicy> listofLP;
	 private LocationPolicy locationPolicy;
	 private DefinedLocation refLocation;
	 
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}


	/* (non-Javadoc)
	 * @see android.app.Service#onCreate()
	 */
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		Toast.makeText(this, "My Location Service Created", Toast.LENGTH_LONG).show();  
        Log.i(TAG, "onCreate");  
		super.onCreate();
		locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
		baseLocation = new Location(LocationManager.GPS_PROVIDER);
		baseLocation.setLatitude(59.832829); //
		baseLocation.setLongitude(17.65033);
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 15000, 0, locationListener);
		Location oldLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		//LocationActivity locationActivity = new LocationActivity();
		//locationActivity.readXML();
		// prehandle the list
		listofLP = LocationActivity.MyList; // should use intent
		 
		// 
	}
	 private final LocationListener locationListener = new LocationListener() 
	    {     
	    	public void onLocationChanged(Location location) 
	    	{     
	    		Log.i(TAG,"Get New Location");
	    		
	    		checkWithinRangeAndPerform(location.getLatitude(),location.getLongitude());// calculate if within the range
	      
	    	}     
	    	private boolean checkWithinRangeAndPerform(double latitude, double longitude) {
	    		
	    		for(int i=0; i< listofLP.size(); i++)
	    		{
	    			locationPolicy = listofLP.get(i);
	    			refLocation = locationPolicy.getDefinedLocation();
	    			float[] cal_result = new float[3];
	    			Location.distanceBetween(latitude, longitude, refLocation.getLatitude(), refLocation.getLongitude(), cal_result);
	    			String distanceMsg = "The current location is "+ Float.toString(cal_result[0]) + " meters away from " + refLocation.getLocationName();
	    			Log.i(TAG, distanceMsg);
	    			if (cal_result[0]< refLocation.getRadius())
	    			{
	    				Toast.makeText(LocationService.this, distanceMsg , Toast.LENGTH_LONG).show(); 
	    				Log.i(TAG,"Gonna perform action soon...");
	    				performAction(locationPolicy.getActions());// perform actions
	    			}
	    			else 
	    			{
	    				Log.i(TAG,"Not in the range of " + refLocation.getLocationName());
	    			}
	    		}
				return true;
			}
			public void onProviderDisabled(String provider){  
	    		
	    	    Log.i(TAG, "Provider now is disabled..");  
	    	}     
	    	public void onProviderEnabled(String provider){  
	    	Log.i(TAG, "Provider now is enabled..");  
	    	}     
	    	public void onStatusChanged(String provider, int status,Bundle extras){ }     
	    	
	    };     
	/* (non-Javadoc)
	 * @see android.app.Service#onDestroy()
	 */
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		
		Toast.makeText(this, "My Location Service Destroy", Toast.LENGTH_LONG).show();  
        Log.i(TAG, "onDestroy"); 
        locationManager.removeUpdates(locationListener);
        super.onDestroy();
	}


	/* (non-Javadoc)
	 * @see android.app.Service#onStart(android.content.Intent, int)
	 */
	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		super.onStart(intent, startId);
		Toast.makeText(this, "My Location Service Started", Toast.LENGTH_LONG).show();  
        Log.i(TAG, "onStart");  
	}
	
	private void performAction(List<DefinedAction> list)
	{
		//new AlertDialog.Builder(LocationActivity.this).setMessage(R.string.welcome).show();
		Iterator it=list.iterator();
        while(it.hasNext()){
        	DefinedAction action = (DefinedAction) it.next();
        	ExecuteAction(action.getActionId()); // execute actions based on the ActionID
        } 
		
	}


	private void ExecuteAction(int actionId) {
		// TODO Auto-generated method stub
		switch (actionId)
		{
		case 1:
			Log.i(TAG, "perform action 1");
			Toast.makeText(this, "perform action 1", Toast.LENGTH_LONG).show(); break;  
		case 2:
			Log.i(TAG, "perform action 2");
			Toast.makeText(this, "perform action 2", Toast.LENGTH_LONG).show(); break;
		case 3:
			Log.i(TAG, "perform action 3");
			Toast.makeText(this, "perform action 3", Toast.LENGTH_LONG).show(); break;
			default:
				Toast.makeText(this, "action code wrong", Toast.LENGTH_LONG).show(); break;
		}
	}

	

}
